/* $Id: core.js 2010-08-31 16:02 idris $ */

function string_to_slug(str) 
{
  str = str.replace(/^\s+|\s+$/g, '')
  	.replace(/[^a-zA-Z0-9 -]/g, '')
	.replace(/\s+/g, '-')
	.replace(/-+/g, '-')
    .toLowerCase();
  
  return str;
};

function toggle_page_edit_tab(link_hide, link_show, tab_id, tab_desc_id, visible)
{
	if (visible){
		$(tab_id).setStyle('display', 'block');
		$(tab_id).removeClass('hidden');
		$(tab_desc_id).setStyle('display', 'none');
		$(tab_desc_id).addClass('hidden');
	}else{
		$(tab_id).setStyle('display', 'none');
		$(tab_id).addClass('hidden');
		$(tab_desc_id).setStyle('display', 'block');
		$(tab_desc_id).removeClass('hidden');
	}
	$(link_hide).setStyle('display', 'none');
	$(link_hide).addClass('hidden');
	$(link_show).setStyle('display', 'inline');
	$(link_show).removeClass('hidden');
};

var page = 
{
	page_id: 0,
	ajax_url: '',
	block: false,
  note: '',
  empty_note: '',
	
	init: function(){
		var self = this;
		$$('.team_title_input').addEvent('blur', function(){
			var admin_id = parseInt(this.id.substr(18));
			var title = this.value;
			if ($('admin_title_'+admin_id).innerHTML == title){
				self.hide_admin_edit(admin_id);
				self.show_admin_info(admin_id);
			}else{
				self.change_title(admin_id, title);
			}
		});
	},
	
	prepare_post: function(page_id){
		var self = this;
		this.page_id = page_id;
		this.edit_mode(true);
	},
	
	edit_mode: function(flag){
		if (flag){
			$('profile_note_link').setStyle('display', 'none');
			$('profile_note_textarea').setStyle('display', 'block');
			$('profile_note_text').setStyle('display', 'none');
			$$('#profile_note_textarea textarea')[0].value = this.note;
			$$('#profile_note_textarea textarea')[0].focus();
		}else{
			$('profile_note_link').setStyle('display', 'block');
			$('profile_note_textarea').setStyle('display', 'none');
			if ($('profile_note_text').innerHTML){
				$('profile_note_text').setStyle('display', 'block');
			}
		}
	},
	
	change_title: function(admin_id, title){
		var self = this;
		
		if (this.block){
			return ;
		}
		this.block = true;
		
		$('admin_title_input_'+admin_id).disabled = true;
		new Request.JSON({
			'url' : self.ajax_url,
			'method' : 'post',
			'data' : {
				'admin_id' : admin_id,
				'title' : title,
				'format': 'json',
				'task' : 'change_title',
				'page_id' : self.page_id
			},
			onSuccess : function(response){
				$('admin_title_'+admin_id).innerHTML = title;
				self.hide_admin_edit(admin_id);
				self.show_admin_info(admin_id);
				self.block = false;
				$('admin_title_input_'+admin_id).disabled = false;
			}
		}).send();
	},
		
	post_note: function(note){
		var self = this;
		if (note.trim() == this.note){
			self.edit_mode(false);
			return ;
		}
		$$('#profile_note_textarea textarea')[0].disabled = true;
		new Request.JSON({
			'url': self.ajax_url+'?page='+self.page_id,
			'method': 'post',
			'data': {
				'note': note,
				'task' : 'post_note',
				'format': 'json'
			},
			onSuccess: function(response){
        self.note = note;
				if (!response.result){
					$('profile_note_text').innerHTML = en4.core.language.translate("There was error.");
				}else{
          if (self.note.trim() == ''){
					  $('profile_note_text').innerHTML = self.empty_note;
          }else{
            $('profile_note_text').innerHTML = response.note;
          }
				}
				$$('#profile_note_textarea textarea')[0].disabled = false;
				self.edit_mode(false);
			}
		}).send();
	},
	
	choose_admins: function(){
		he_contacts.box('page', 'getUsersForAdmin', 'page.add_admins', en4.core.language.translate('Add admins'), {page_id:this.page_id});
	},
	
	add_admins: function(admins){
		var self = this;
		if (this.block){
			return ;
		}
		this.block = true;
		new Request.JSON({
			'url': self.ajax_url,
			'method': 'post',
			'data': {
				'user_ids': admins,
				'format': 'json',
				'task' : 'add_admins',
				'page_id': self.page_id
			},
			onSuccess: function(response){
				self.block = false;
				window.location.href = window.location.href;
			}
		}).send();
	},
	
	hide_admin_info: function(admin_id){
		$('admin_title_'+admin_id).addClass('hidden');
		$('admin_title_edit_'+admin_id).addClass('hidden');
		
		$('admin_title_'+admin_id).removeClass('visible');
		$('admin_title_edit_'+admin_id).removeClass('visible');
	},
	
	show_admin_info: function(admin_id){
		$('admin_title_'+admin_id).addClass('visible');
		$('admin_title_edit_'+admin_id).addClass('visible');
		
		$('admin_title_'+admin_id).removeClass('hidden');
		$('admin_title_edit_'+admin_id).removeClass('hidden');
	},
	
	show_admin_edit: function(admin_id){
		$('admin_title_input_box_'+admin_id).addClass('visible');
		$('admin_title_input_box_'+admin_id).removeClass('hidden');
	},
	
	hide_admin_edit: function(admin_id){
		$('admin_title_input_box_'+admin_id).addClass('hidden');
		$('admin_title_input_box_'+admin_id).removeClass('visible');
	},
	
	focus_input: function(admin_id){
		$('admin_title_input_'+admin_id).focus();
	},
	
	edit_admin_title: function(admin_id){
		this.hide_admin_info(admin_id);
		this.show_admin_edit(admin_id);
		this.focus_input(admin_id);
	}
};

var pages_map = 
{
	pages_array: {},
	markers_array: {},
	map_bounds: {},
	zoom: 4,
  constructed: false,
	
	construct: function(pages_array, markers_array, zoom, map_bounds){
		this.pages_array = pages_array;
		this.markers_array = markers_array;
		this.map_bounds = map_bounds;
		this.zoom = zoom;
		this.init();
		this.show_map();
    this.constructed = true;
	},
	
	init: function(){
		window.map = new GMap2(document.getElementById("map_canvas"));
		window.map.setUIToDefault();
	},

	show_map: function() {
		if( this.markers_array.length==0 ) {return false;}
		window.map.clearOverlays();
		
		for( var i=0; i<this.markers_array.length; i++ )
		{
			var marker = this.markers_array[i];
			var point = new GLatLng(marker.lat, marker.lng);
			marker_obj = new GMarker(point);
			window.map.addOverlay(marker_obj);
			if (!marker.desc) {marker.desc='';}
			marker_obj.bindInfoWindow('<table width="500"><tr valign="top"><td width="110"><img src="' + marker.pages_photo + '" width="100"></td><td width="400"><h3 style="margin-top:0; margin-bottom:6px;"><a href="'+marker.url+'">' + marker.title + '</a></h3>' + marker.desc + '</td></tr></table>');
		}
		
		window.map.setCenter(new GLatLng(marker.lat, marker.lng), 4);
		if (this.map_bounds && this.map_bounds.min_lat && this.map_bounds.max_lng && this.map_bounds.min_lat && this.map_bounds.max_lng) {
			var bds = new GLatLngBounds(new GLatLng(this.map_bounds.min_lat, this.map_bounds.min_lng), new GLatLng(this.map_bounds.max_lat, this.map_bounds.max_lng));
		}
		if (this.map_bounds && this.map_bounds.map_center_lat && this.map_bounds.map_center_lng) {
			window.map.setCenter(new GLatLng(this.map_bounds.map_center_lat, this.map_bounds.map_center_lng), 4);
		} else {
			window.map.setCenter(new GLatLng(marker.lat, marker.lng), this.zoom);
		}
		if (bds) {window.map.setZoom(window.map.getBoundsZoomLevel(bds));}
	}
};

var he_word_completer = {
	prepend_word : '',
	input : null,
	completer : null,
	default_value : '',
	ajax_url : '',
	block_request : false,

	init : function(){
		var self = this;
    var ignored_keys = ['left', 'right', 'home', 'end', 'delete', 'backspace'];

		window.addEvent('domready', function(){
			$(self.input).addEvent('keyup', function(e){
        if (ignored_keys.contains(e.key)) {
          return;
        }
        self.complete(this.value);
			});
      $(self.input).addEvent('blur', function(){
        self.complete(this.value);
        if (!self.block_request){
          self.block_request = true;
          self.validate(this.value);
          self.block_request = false;
        }
      })
		});
	},

	complete : function(value){
		value = string_to_slug(value);
		if (value != ""){
			$(this.completer).innerHTML = this.prepend_word + value;
			$(this.input).value = value;
		}else{
			$(this.completer).innerHTML = this.prepend_word + this.default_value;
		}
	},
	
	validate : function(url){
		var self = this;
		new Request.JSON({
			'url' : self.ajax_url,
			'method' : 'post',
			'data' : {
				'url' : url,
				'format' : 'json'
			},
			onSuccess : function(response){
				self.highlight($(self.input), response);
			}
		}).send();
	},
	
	highlight : function($element, response){
		$$('.success_image').each(function($item){
      $item.dispose();
    });
    $$('.error_image').each(function($item){
      $item.dispose();
    });
    $element = $($element);
		$element.removeClass('error');
		$element.removeClass('success');		
		if (response.success){
			$img = new Element('div', {'class' : 'success_image'});
			$img.innerHTML = "<span class='success_message'>";
			$element.addClass('success');
		}else{
			$img = new Element('div', {'class' : 'error_image'});
			$img.innerHTML = "<span class='error_message'>";
			$element.addClass('error');
		}
		$img.innerHTML += response.message+"</span>";
    $img = $($img);
		$img.inject($element, 'after')
	}
};

var page_manager = {
	page_num : 1,
	ajax_url: '',
	field_ids: {},	
	
	init : function(){
		var self = this;
		var default_value = "Search";
		window.addEvent('domready', function(){
			$('extra-keyword').value = default_value;
			$('submit').addEvent('click', function(e){
				e.stop();
				$('extra-city').value = '';
				$('extra-tag_id').value = '';
				self.page_num = 1;
				self.getPages();
			});
			$('extra-keyword').addEvents({
				'focus' : function(){
					if (this.value == default_value){
						this.value = "";
					}
				},
				'blur' : function(){
					if (this.value == ""){
						this.value = default_value;
					}
				}
			});
			$$('#filter_form div ul li').setStyle('display', 'none');
			$('extra-keyword').getParent().setStyle('display', 'block');
			if ($('profile_type')){
				$('profile_type').getParent().setStyle('display', 'block');
			}
			$('submit').getParent().setStyle('display', 'block');
			
			var $elements = $$('#filter_form div ul li input, #filter_form div ul li select, #filter_form div ul li textarea');
			
			if ($('profile_type')){
				$('profile_type').addEvent('change', function(){
					var data = self.field_ids;
					for (var i = 0; i < $elements.length; i++){
						var id = parseInt($elements[i].id.substr(6, 2));
						if (!id){
							continue;
						}
						if (data[id] == this.value){
							$elements[i].getParent().setStyle('display', 'block');
						}else{
							$elements[i].getParent().setStyle('display', 'none');
						}
					}
				});
			}
		});
	},
	
	getPages : function(){
		var self = this;
		if ($('extra-keyword').value == 'Search'){
			$('extra-keyword').value = '';
		}
		
		if ($('page_loader_browse')){
			$('page_loader_browse').removeClass('hidden');
		}
		
		var query = $('filter_form').toQueryString();
		new Request.JSON({
			'url' : self.ajax_url+'/'+self.page_num+'?'+query,
			'method' : 'post',
			'data' : {
				'format' : 'json'
			},
			onSuccess : function(response){
				$('page_list_container').innerHTML = response.html;
				if (response.count > 0){
          if (pages_map.constructed){
				    pages_map.construct( null, response.markers, 4, response.bounds);
          }
				}
				if ($('extra-tag_id').value){
				  if ($('page_tag_info')){
				    if ($('tag_'+$('extra-tag_id').value)){
    					$('page_tag_info').innerHTML = '<ul class="form-notices"><li>'+en4.core.language.translate('Pages sorted by')+' <span class="bold">'+$('tag_'+$('extra-tag_id').value).innerHTML+'</span> '+en4.core.language.translate('tag')+'. [<a href="javascript:void(0)" class="bold" onClick="page_manager.setTag(0);">x</a>]</li></ul>';
    					$('page_tag_info').removeClass('hidden');
				    }
				  }
				}else{
				  if ($('page_tag_info')){
  					$('page_tag_info').innerHTML = "";
  					$('page_tag_info').addClass('hidden');
				  }
				}
				if ($('page_loader_browse')){
					$('page_loader_browse').addClass('hidden');
				}
			}
		}).send();
	},
	
	setSort : function(sort){
		$('extra-sort').value = sort;
		this.getPages();
	},
	
	setView : function(view){
		if (view == 'map'){
			$('page_list_cont').setStyle('display', 'none');
			$('map_canvas').setStyle('position', 'relative');
			$('map_canvas').setStyle('top', '0px');
		}else{
			$('page_list_cont').setStyle('display', 'block');
			$('map_canvas').setStyle('position', 'absolute');
			$('map_canvas').setStyle('top', '10000px');
		}
	},
	
	setCategory : function(category){
		$('filter_form').reset();
		$('profile_type').value = category;
		
		this.getPages();
	},
	
	setLocation : function(city){
		$('filter_form').reset();
		$('extra-city').value = city;
		this.getPages();
	},

	setPage : function(page){
		this.page_num = page;
		this.getPages();
	},
	
	setTag : function(tag_id){
		this.page_num = 1;
		var sort = $('extra-sort').value;
		$('filter_form').reset();
		
		$('extra-sort').value = sort;
		$('extra-tag_id').value = tag_id;
		this.getPages();
	}
};

var page_search = {
	
	url: '',
	filter_url: '',

	page_id: 0,

	p: 1,

	keyword: '',

	placeholder: 'Search',

	element: 'page-search-field',
	$element: null,

	container: 'page-search-results',
	$container: null,

	tab: 'page-search-tab',
	$tab: null,

	tab_container: 'page-search-tab-container',
	$tab_container: null,

	loader: 'page-search-loader',
	$loader: null,

	middle: 'div.layout_core_container_tabs',
	$middle: null,

	filter_form: 'page-search-filter-form',

	tag_container: 'page-tag-results',
	$tag_container: null,

	timeout: null,
	block: false,

	toggle_timer: null,

	init: function(){
		var self = this;
		
		self.$middle = $$(self.middle)[0];
		self.init_more_block();
		self.init_tag_cloud();
		
		self.$element = $(self.element);
		self.$container = $(self.container);
		self.$tab = $(self.tab);
		self.$tab_container = $(self.tab_container);
		self.$loader = $(self.loader);

		var left = page_search.$element.getParent().getParent().offsetLeft;
		var top = page_search.$element.getParent().getParent().offsetTop + 30;
		
		self.$container.setStyle('left', left);
		self.$container.setStyle('top', top);

		if (self.$element){
			self.$element.addEvents({
				'keyup': function(){
					var value = this.value;
					if (!value){
						return ;
					}
					if (self.keyword != value){
						window.clearTimeout(self.timeout);
						self.timeout = window.setTimeout(function(){
							self.search(value);
						}, 1000);
					}
				},
				'focus': function(){
					var value = this.value;
					if (value == self.placeholder){
						this.value = '';
						$(this).removeClass('inactive');
					}else if (value == ''){
						this.value = self.placeholder;
						$(this).addClass('inactive');
					}
				},
				'blur': function(){
					var value = this.value;
					if (value == ''){
						this.value = self.placeholder;
						$(this).addClass('inactive');
					}
				}
			});
		}
		if (self.$container){
			self.$container.addEvents({
				'mouseout': function(){
					window.clearTimeout(self.toggle_timer);
					self.toggle_timer = window.setTimeout(function(){
						self.close();
					}, 1000);
				},
				'mouseover': function(){
					window.clearTimeout(self.toggle_timer);
				}
			});
		}
	},

	init_tag_cloud: function(){
		var self = this;
		
		if ($(self.tag_container)){
			return $(self.tag_container);
		}
		
		this.$middle = $$(self.middle)[0];
		var $container = new Element('div', {'id': self.tag_container, 'class': self.tag_container + ' hidden'});
		this.$middle.appendChild($container);
		this.$tag_container = $container;

		return $container;
	},
	
	search: function(keyword){
		var self = this;
		
		if (this.block){
			return ;
		}
		this.block = true;
		
		self.keyword = keyword;
		self.show_loader();

		new Request.JSON({
			'url': self.url,
			'method': 'post',
			'data': {
				'keyword': keyword,
				'page_id': self.page_id,
				'p': self.p,
				'format': 'json'
			},
			onSuccess: function(response){
				var html = response.html ? response.html : '';
				var tab_html = response.tab_html ? response.tab_html : '';
				self.block = false;

				self.$container.set('html', html);
				if (!html){
					self.hide_results();
				}else{
					var mored = !self.$tab_container.hasClass('hidden') && self.$tab_container.getStyle('display') != 'none';
					if (!mored){
						self.show_results();
					}
				}
				
				self.$tab.set('html', tab_html);
				self.hide_loader();
			}
		}).send();
	},

	filter: function($form){
		var self = this;
		$form = $($form);
		self.show_loader();

		new Request.JSON({
			'url': self.filter_url+'?'+$form.toQueryString(),
			'method': 'post',
			'data': {
				'page_id': self.page_id,
				'format': 'json'
			},
			onSuccess: function(response){
				var html = response.html ? response.html : '';
				
				self.$tab.set('html', html);
				self.hide_loader();
			}
		}).send();
	},

	close: function(){
		this.hide_results();
	},

	init_more_block: function(){
		var self = this;
		var $middle = this.$middle;
		var $container = new Element('div', {'id': self.tab_container, 'class': 'page-search-tab-container hidden'});
		var $items = new Element('div', {'id': self.tab, 'class': 'page-search-tab'});

		$container.set('html', $(this.filter_form).innerHTML);
		$container.appendChild($items);
		$middle.appendChild($container);
		$(this.filter_form).dispose();
		
		return $container;
	},

	more: function(){
		$$(this.$middle.getElements('.generic_layout_container')).each(function($element){
			$element.setStyle('display', 'none');
		});
		
		this.$tab_container.removeClass('hidden');
		this.$tab_container.setStyle('display', 'block');

		this.$tag_container.addClass('hidden');
		this.$tag_container.setStyle('display', 'none');
		
		this.close();

		$$($('main_tabs').getElements('li.active')).each(function($li){
			$li.removeClass('active');
		});

		$$($('search_filter_form').getElements('input[type=checkbox]')).each(function($checkbox){
			$checkbox.checked = true;
		});

		$('search-keyword').value = this.keyword;
	},

	tag_action: function(){
		$$(this.$middle.getElements('.generic_layout_container')).each(function($element){
			$element.setStyle('display', 'none');
		});

		if (this.$tab_container){
			this.$tab_container.addClass('hidden');
			this.$tab_container.setStyle('display', 'none');
		}

		this.$tag_container.removeClass('hidden');
		this.$tag_container.setStyle('display', 'block');
		this.$tag_container.set('html', '<div class="page-tag-cloud-loader"><img src="'+window.en4.core.baseUrl+'application/modules/Page/externals/images/loader_search.gif" /><span class="loading_span"> Loading...</span></div>');

		this.close();

		$$($('main_tabs').getElements('li.active')).each(function($li){
			$li.removeClass('active');
		});
	},

	show_results: function(){
		var self = this;
		
		this.$container.setStyle('opacity', 0);
		this.$container.removeClass('hidden');

		var fx = new Fx.Morph(this.$container.id, {duration: 500, transition: Fx.Transitions.Sine.easeOut});
		fx.start({
				'opacity': 1
		});
	},

	hide_results: function(){
		var self = this;
		if (!this.$container){
			return ;
		}
		var fx = new Fx.Morph(this.$container.id, {duration: 500, transition: Fx.Transitions.Sine.easeOut});
		fx.start({
				'opacity': 0
		});

		window.setTimeout(function(){
			self.$container.addClass('hidden');
		}, 500);
	},

	show_loader: function(){
		this.$loader.setStyle('background-image', 'url(' + window.en4.core.baseUrl + 'application/modules/Page/externals/images/loading.gif)');
	},

	hide_loader: function(){
		this.$loader.setStyle('background-image', 'url(' + window.en4.core.baseUrl + 'application/modules/Page/externals/images/viewpage.png)');
	},

	view: function(type, id){
		switch (type){
			case 'pagealbumphoto':{
				page_album.init_album();
				page_album.view_photo(id);
			}
			break;
			case 'pagealbum': {
				page_album.album = id;
				page_album.init_album();
				page_album.view(id);
			}
			break;
			case 'pagevideo': {
				page_video.init_video();
				page_video.view_comments(id);
			}
			break;
			case 'pageblog': {
				page_blog.blog_id = id;
				page_blog.init_blog();
			}
			break;
			case 'song': {
				page_music.init_music();
				page_music.view_song(id);
			}
			break;
			case 'playlist': {
				page_music.playlist_id = id;
				page_music.init_music();
				page_music.view(id);
			}
			break;
		}

		this.close();
		return false;
	},

	search_by_tag: function(tag_id){
		var self = this;
		self.tag_action();
		
		new Request.JSON({
			'url': self.tag_url,
			'method': 'post',
			'data': {
				'tag_id': tag_id,
				'page_id': self.page_id,
				'format': 'json'
			},
			onSuccess: function(response){
				self.$tag_container.set('html', response.html);
			}
		}).send();
	}

}